<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MQTT HEX Data Receiver</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
    <!-- 或者使用其他版本 -->
</head>
<body>
    <h1>MQTT HEX Data Receiver</h1>
    <div id="status"></div>
    <div id="message"></div>
    <script>
        // 连接到MQTT broker
        var client = new Paho.MQTT.Client("172.247.21.60", Number(6091), "clientIdc");

        // 设置回调
        function onConnect() {
            console.log("Connected");
            // 订阅主题
            client.subscribe("test1/1");
        }

        function onMessage(message) {
            document.getElementById('message').innerHTML = "Received: " + message.payloadString;
            // 如果消息是十六进制格式，可以转换为可读字符串或处理为其他形式
            try {
                let hexData = message.payloadString; // 假设这里的数据已经是十六进制字符串
                let bytes = hexToArrayBuffer(hexData);
                let textDecoder = new TextDecoder('utf-8');
                let text = textDecoder.decode(new Uint8Array(bytes));
                document.getElementById('message').innerHTML += "<br>Decoded: " + text;
            } catch (e) {
                console.error("Error decoding message:", e);
            }
        }

        function hexToArrayBuffer(hex) {
            var arrayBuffer = new ArrayBuffer(hex.length / 2),
                byteArray = new Uint8Array(arrayBuffer);

            for (var i = 0; i < hex.length; i += 2) {
                byteArray[i / 2] = parseInt(hex.substr(i, 2), 16);
            }

            return arrayBuffer;
        }

        // 连接设置
        var options = {
            timeout: 3,
            onSuccess: onConnect,
            useSSL: true
        };

        // 尝试连接
        client.connect(options);

        // 设置消息监听器
        client.onMessageArrived = onMessage;

        // 其他逻辑...
    </script>
</body>
</html>